package ua.org.tumakha.resume.xml.transform;

import java.io.File;
import java.io.FileOutputStream;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Yuriy Tumakha
 */
public class XslTransformer implements XmlTransformer {

    private static final Log log = LogFactory.getLog(XslTransformer.class);
    private static final TransformerFactory tFactory = TransformerFactory.newInstance();;
    protected static File outputDirectory = new File("");
    protected Transformer transformer;
    private String fileExtension = ".xml";

    public XslTransformer(File styleSheetFile) throws TransformerConfigurationException {
        transformer = tFactory.newTransformer(new StreamSource(styleSheetFile));
    }

    public XslTransformer(File styleSheetFile, String fileExtension) throws TransformerConfigurationException {
        this(styleSheetFile);
        setFileExtension(fileExtension);
    }

    public boolean transform(File xmlSource) throws Exception {
        File resultFile = getResultFile(xmlSource);
        transformer.transform(new StreamSource(xmlSource), new StreamResult(new FileOutputStream(resultFile)));
        return true;
    }

    protected File getResultFile(File xmlSource) {
        String resultFile = getOutputDirectory().getAbsolutePath() + File.separator
                + xmlSource.getName().replaceFirst(".xml", "") + getFileExtension();
        log.info("Transform \"" + xmlSource.getName() + "\" to \"" + resultFile + "\".");
        return new File(resultFile);
    }

    protected String getFileExtension() {
        return fileExtension;
    }

    protected void setFileExtension(String fileExtension) {
        this.fileExtension = fileExtension;
    }

    public static File getOutputDirectory() {
        return outputDirectory;
    }

    public static void setOutputDirectory(File outputDirectory) {
        XslTransformer.outputDirectory = outputDirectory;
    }

}
